package Algorithm.Tree;

/**
 * @Author cj
 * @Date 2022/11/3 21:39
 */
public class nodeNum {
    static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int val) {
            this.value = val;
        }
    }

    public int nodeNum1(Node head) {
        if (head == null) {
            return 0;
        }
        return bs(head, 1, mostLeftLevel(head, 1));
    }

    private int bs(Node node, int l, int h) {
        if (l == h) { // 到最下一层节点，没有子节点，终止条件，返回1
            return 1;
        }
        // 右子树最左节点到达最后一层
        if (mostLeftLevel(node.right, l + 1) == h) {
            // 1 << n 表示1左移n位，相当于2的n次
            return (1 << (h-1)) + bs(node.right, l + 1, h);
        } else { // 未到达
            return (1 << (h - l - 1)) + bs(node.left, l + 1, h);
        }
    }

    private int mostLeftLevel(Node node, int level) {
        while (node != null) {
            level ++;
            node = node.left;
        }
        return level - 1;
    }
}
